<template>
  <div class="app-container">
    <el-table
      v-loading="loading"
      :data="songList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="专辑名" align="center" prop="albumName" /> -->
      <el-table-column label="歌名" align="center" prop="songName" />
      <el-table-column label="图片" align="center" prop="imgUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="音乐文件路径" align="center" prop="fileUrl" /> -->
      <el-table-column label="歌手" align="center" prop="singer" />
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handlePlay(scope.row)"
            >播放</el-button
          >
          <el-button size="mini" type="text" icon="el-icon-download"
            ><a :href="scope.row.fileUrl" download>下载</a></el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >取消收藏</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { addHistory } from "@/api/history/history";
import {
  listFavorite,
  getFavorite,
  delFavorite,
  addFavorite,
  updateFavorite,
} from "@/api/favorite/favorite";
import {
  listFavoriteByUserId,
  listSong,
  getSong,
  delSong,
  addSong,
  updateSong,
} from "@/api/song/song";
export default {
  name: "Favorite",
  data() {
    return {
      songList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户收藏表格数据
      favoriteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        songId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "收藏时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.queryParams.userId = localStorage.getItem("userId"); // 获取当前登录用户ID
    this.getList();
    this.getSongList();
  },
  methods: {
    /** 查询音乐信息列表 */
    getSongList() {
      this.loading = true;
      listFavoriteByUserId(this.queryParams.userId).then((response) => {
        // console.log("音乐获取", response);
        this.songList = response.rows;
        this.total = response.total;
        console.log("songList", this.songList);
        this.loading = false;
      });
    },
    /** 查询收藏列表 */
    getList() {
      this.loading = true;
      listFavorite(this.queryParams).then((response) => {
        this.favoriteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        favoriteId: null,
        userId: null,
        songId: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.favoriteId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户收藏";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const favoriteId = row.favoriteId || this.ids;
      getFavorite(favoriteId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户收藏";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.favoriteId != null) {
            updateFavorite(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFavorite(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const data = {
        userId: this.queryParams.userId,
        songId: row.songId,
      };

      this.$modal
        .confirm("是否确认取消收藏该歌曲？")
        .then(function () {
          return delFavorite(data);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("取消收藏成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "favorite/favorite/export",
        {
          ...this.queryParams,
        },
        `favorite_${new Date().getTime()}.xlsx`
      );
    },
    /** 播放按钮操作 */
    handlePlay(row) {
      const data = {
        songId: row.songId,
        userId: localStorage.getItem("userId"),
      };
      //记录用户播放次数
      addHistory(data).then((res) => {
        console.log("播放次数", res);
      });
      //添加用户的行为信息到本地存储
      const index = localStorage.getItem("index");
      localStorage.removeItem("index");

      const userActionData = JSON.stringify({
        userId: localStorage.getItem("userId"),
        songId: row.songId,
        action: "play",
      });
      localStorage.setItem(parseInt(index) + 1, userActionData);

      //index加一
      localStorage.setItem("index", parseInt(index) + 1);
      
      this.$router.push({
        path: "/player",
        query: { songId: row.songId },
      });
    },
  },
};
</script>
